package chapter8.eg7;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.List;

public class FixedLengthFrameDecoder extends ByteToMessageDecoder {
  private final int frameLength;

  public FixedLengthFrameDecoder(int frameLength) {
    if (frameLength <= 0) {
      throw new IllegalArgumentException("frameLength cannot be lower than 0");
    }

    this.frameLength = frameLength;
  }

  @Override
  protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    while (in.readableBytes() >= frameLength) {
      ByteBuf buf = in.readBytes(frameLength);
      out.add(buf);
    }
  }
}
